/*
 
 */
#include <EEPROM.h>

int ledPin =  9;    // LED connected to digital pin 9
int ledPin2 = 13;    // LED connected to digital pin 13
volatile int tmp = 0;
int input = 0;
volatile int delayvalue = 500;

//This function will write a 2 byte integer to the eeprom at the specified address and address + 1
void EEPROMWriteInt(int p_address, int p_value)
	{
	byte lowByte = ((p_value >> 0) & 0xFF);
	byte highByte = ((p_value >> 8) & 0x0F);

	EEPROM.write(p_address, lowByte);
	EEPROM.write(p_address + 1, highByte);
	}

//This function will read a 2 byte integer from the eeprom at the specified address and address + 1
unsigned int EEPROMReadInt(int p_address)
	{
	byte lowByte = EEPROM.read(p_address);
	byte highByte = EEPROM.read(p_address + 1);

  	return ((lowByte << 0) & 0xFF) + ((highByte << 8) & 0x0F00);
	}


// The setup() method runs once, when the sketch starts

void setup()   {                
  // initialize the digital pin as an output:
  pinMode(ledPin, OUTPUT);  
  pinMode(ledPin2, OUTPUT);  
  Serial.begin(9600);  

  pinMode(2, INPUT);  
  attachInterrupt(0, int_handler, RISING); // 0 -> pin2 | 1 -> pin3
  
  delayvalue = EEPROMReadInt(0 /*addr*/);
}

// the loop() method runs over and over again,
// as long as the Arduino has power

void loop()                     
{
  digitalWrite(ledPin, HIGH);   // set the LED on
  digitalWrite(ledPin2, LOW);   // set the LED off
  //Serial.println("LED ON");
  delay(delayvalue);                  // wait for a second
  digitalWrite(ledPin, LOW);    // set the LED off
  digitalWrite(ledPin2, HIGH);    // set the LED on
  //Serial.println("LED OFF");
  delay(delayvalue);                  // wait for a second

  while (Serial.available() > 0) {
    input = Serial.read();
    switch(input){
      case '?':
      Serial.println("Differnt command options: up (u) | down (d)"); break;
      case 'u':
      Serial.println("up"); delayvalue += 250; break;
      case 'd':
      Serial.println("down"); delayvalue -= 250; break;
      case 'v':
      Serial.println(delayvalue); break;
      case 'w':
      Serial.println("writing EEPROM value"); EEPROMWriteInt(0 /*addr*/, delayvalue); break;
      case 'r':
      Serial.println("resetting EEPROM value"); EEPROMWriteInt(0 /*addr*/, 500); delayvalue = 500; break;
    }
  }
  
}

void int_handler()
{
  tmp++;
  //Serial.println("Interrupt received !!!!"); 
}










